package com.feib.ebilling.job;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;


import com.feib.ebilling.job.service.TransferFeedbackService;






@Service("transferFeedback")
public class TransferFeedback {

	public final static Logger logger = LoggerFactory.getLogger(TransferFeedback.class);

	public static final SimpleDateFormat BASIC_DATE_TIME_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	private static ApplicationContext SPRING_CTX = null;

	@Resource(name="transferFeedbackService")
	private TransferFeedbackService transferFeedbackService;

	/** 輸入參數對應的 指定檔案類型，參數代號規則同 FILE_FORMAT */
	private static Map<String,String> Channel_Field =  new HashMap<String, String>();
	static{
		Channel_Field.put("ALL", "ALL");
		Channel_Field.put("D", "D");
		Channel_Field.put("E", "E");
		Channel_Field.put("F", "F");
		Channel_Field.put("G", "G");
		Channel_Field.put("H", "H");
	}

	private static List<String> Channels =  new ArrayList<String>();
	static{
		Channels.add("D");
		Channels.add("E");
		Channels.add("F");
		Channels.add("G");
		Channels.add("H");

	}




	/**
	 * 可以參數針對某個通路、傳輸日期重跑。
	 * 若該筆帳單資料已批次產生過，就不能再讓他二次寫入了
	 */
	public static void main(String[] args) {

		SPRING_CTX = new ClassPathXmlApplicationContext(
				new String[] {"applicationContext-config.xml",	"applicationContext-dao.xml", "applicationContext-properties.xml"});


		Date start = new Date();
		logger.info("[開始]  批次  - {}", BASIC_DATE_TIME_FORMAT.format(start));

		try 
		{
			TransferFeedback job = (TransferFeedback)SPRING_CTX.getBean("transferFeedback");

			/* 根據參數 判斷要執行的檔案類型 跟交割日期  */
			if (null == args || 0 == args.length)
			{
				/* 處理系統日當日所有類型 */
				job.execute();
			}
			else
			{
				/* 指定通路 自動抓 */
				if (1 == args.length)
				{					
					/* 指定日期 */  
					Date fbtime = null;
					try {
						fbtime = new SimpleDateFormat("yyyyMMdd").parse(args[0]);
						job.execute(Channels,fbtime);
					} catch (ParseException e) {
						throw new RuntimeException("指定日期格式錯誤，應為 yyyyMMdd，例如 : 20120813");
					}

				}
				else
				{
					if (2 == args.length){

						try {

							/* 指定日期參數[0]，指定通路參數[1]*/


							/* 指定日期 */  
							Date fbtime = null;
							try {
								fbtime = new SimpleDateFormat("yyyyMMdd").parse(args[0]);
							} catch (ParseException e) {
								throw new RuntimeException("指定日期格式錯誤，應為 yyyyMMdd，例如 : 20120813");
							}
							String fileFormat=Channel_Field.get(args[1]);
							if(StringUtils.isNotEmpty(fileFormat)){
								/* 處理 指定日期參數[0]，指定通路參數[1]  */
								List<String> channel =  new ArrayList<String>();
								channel.add(fileFormat);
								job.execute(channel, fbtime);

							}else{
								throw new RuntimeException("指定時間 "+ args[0]+" 指定通路參數"+ args[1]+"無法取得對應的處理類型");
							}
						} catch (RuntimeException e) {
							logger.error(e.getMessage(), e);
							throw new RuntimeException("invalide frist argument, must be number");

						}

					}	
				}
			}



		}
		catch (Exception e)
		{
			logger.error(e.getMessage(), e);
		}
		finally
		{
			Date end = new Date();
			logger.info("[結束]  批次 - {}", BASIC_DATE_TIME_FORMAT.format(end));
			logger.info("共費時 - " + ((end.getTime() - start.getTime()) / 1000) + " 秒");

		}
	}

	/**
	 * 執行批次
	 * @throws Exception 
	 */
	public void execute() throws Exception
	{			
		Date sysDate=new  Date();
		logger.info("取得執行日期-系統日期：{}", sysDate);	
		this.execute(Channels,sysDate);

	}

	/**
	 * 執行批次
	 * @throws Exception 
	 */
	public void execute(List<String> dealChannels,Date fbtime) throws Exception
	{



		/* 檢查有沒有重複*/
		boolean passed = true;

		List<String> hasDoneChannels =  new ArrayList<String>();
		/* 檢查帳單資料是否已批次產生 */
		hasDoneChannels=transferFeedbackService.hasProduced(dealChannels, fbtime);
		if(CollectionUtils.isNotEmpty(hasDoneChannels)){
			/*已有批次資料*/
			passed=false; 
		}
		if(passed && CollectionUtils.isNotEmpty(dealChannels)){
			/*製作超商*/
			int count =transferFeedbackService.doTransferFeedback(dealChannels, fbtime);

			logger.info("產生筆數 {}",count);		
			/*製作郵局*/
		}else if(!passed){
			/*已有批次資料*/
			logger.error("[錯誤]channel {},銷帳日期{} 於資料表TRANSFER_LOG 中已有 批次產生紀錄.", hasDoneChannels,fbtime);		   
		}else{

			logger.info("無需處理資料");		   

		}



	}



}
